<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/6
 * Time: 13:04
 */

namespace App\Model\Backstage;

use App\Http\Controllers\Backstage\AreaController;
use App\Model\Account\SystemType;
use App\Model\Account\Type;
use App\Model\Base;
use App\Model\Backstage\RoomInfo;

use App\Model\Mobile\MobilePlan;
use Illuminate\Support\Facades\DB;
use Validator;


class NullObject{}

class Customers extends Base
{
    public $customers;
    public $mobile_plan;
    public $customersfollow;
    public $customerfollowsource;
    protected $achievement_table;
    protected $room_table;
    protected $room_wordbook;
    protected $comm_cus = 2;  //公客对应ID   此数据后期对照正式ID值
    protected $private_cus = 1; //私客对应ID   此数据后期对照正式ID值
    public function __construct()
    {
        parent::__construct();
        $this->customers = 'customers_'.$this->branch_id;
//        $this->customers = 'customers';

//        $this->mobile_plan = 'mobile_plan';//移动端标记表
        $this->mobile_plan = 'mobile_plan_'.$this->branch_id;


        $this->achievement_table = 'achievement_'.$this->branch_id;
//        $this->achievement_table = 'achievement';  //接口对接完成更换为上面表名

//        $this->customersfollow = 'customer_follow';//客源跟进表
        $this->customersfollow = 'customer_follow_'.$this->branch_id;

//       $this->customerfollowsource = 'customer_follow_source';//客源跟进提醒表
        $this->customerfollowsource = 'customer_follow_source_'.$this->branch_id;

//      $this->room_table = 'room_info';//接口对接完成更换为正式表名
        $this->room_table = 'room_info_'.$this->branch_id;

//        $this->room_wordbook = 'room_wordbook';
        $this->room_wordbook = 'room_wordbook_'.$this->branch_id;

    }

    /**
     * @param $pageLimit
     * @param array $where
     * @param $keywords
     * @param $appOrPc  pc传的是0， app传的是1
     * @return bool
     */
    public function listCustomers($pageLimit, $where = [], $keywords, $appOrPc)
    {
        $file =[$this->customers.'.c_id','c_numbering','c_user_name', 'c_user_phone', 'c_contact', 'c_contact_type', 'c_id_card', 'c_address',
                    'c_trading_type', 'c_buy_status', 'c_private_guest', 'c_quality', 'c_secondary_area', 'c_area_address','c_room', 'c_room_json', 'c_position',
                    'c_planning', 'c_level', 'c_acreage_max', 'c_acreage_min', 'c_price_max', 'c_price_min',  'c_rent_price_max', 'c_rent_price_min',
                    'c_entrust_time', 'c_entrust_type', 'c_source_type', 'c_user_level', 'c_live_type', 'c_professional_type',
                    'c_user_intention', 'c_time_limit', 'c_use_type', 'c_floor', 'c_room_type', 'c_toward', 'c_decorate_type',  'c_payment_type', 'c_complete', 'c_parking',
                    'c_situation', 'c_fence', 'c_electricity', 'c_number_of_layers',  'c_industry', 'c_wc', 'c_lot', 'c_pay_type', 'c_remark', 'c_store_id',
                    'name', 'c_employees_id', 'u_username','c_store_id','c_employees_id',
                    DB::raw('from_unixtime(c_followup_time) as c_followup_time'),
                    DB::raw('from_unixtime(c_created_at) as c_created_at'),
                    DB::raw('from_unixtime(c_update_at) as c_update_at')
                ] ;
        if ($appOrPc == 0) { //PC端查询  客源列表
            if($keywords != ''){
                $list = DB::table($this->customers)
                    ->leftjoin('user', 'c_employees_id', '=', 'u_id')
                    ->leftjoin('department', 'c_store_id', '=', 'id')
                    ->where(function ($query) use($where, $keywords){
                        $query->where($where)->where('c_user_name', 'like', '%'.$keywords.'%');
                    })->orWhere(function ($query) use($where, $keywords) {
                        $query->where($where)->where('c_user_phone', 'like', '%'.$keywords.'%');
                    })->orWhere(function ($query) use($where, $keywords){
                        $query->where($where)->where('c_address', 'like', '%'.$keywords.'%');
                    })->orWhere(function ($query) use($where, $keywords){
                        $query->where($where)->where('c_numbering', 'like', '%'.$keywords.'%');
                    })
                    ->select($file)
                    ->orderBy('c_id', 'desc')
                    ->paginate($pageLimit);
            }else{
                $list = DB::table($this->customers)
                    ->leftjoin('user', 'c_employees_id', '=', 'u_id')
                    ->leftjoin('department', 'c_store_id', '=', 'id')
                    ->where($where)
                    ->select($file)
                    ->orderBy('c_id', 'desc')
                    ->paginate($pageLimit);
            }
        } else {  //APP端查询客源列表
            if($keywords != ''){
                $list = DB::table($this->customers)
                    ->leftjoin('user', 'c_employees_id', '=', 'u_id')
                    ->leftjoin('department', 'c_store_id', '=', 'id')
                    ->where(function ($query) use($where, $keywords){
                        $query->where($where)->where('c_user_name', 'like', '%'.$keywords.'%');
                    })->orWhere(function ($query) use($where, $keywords) {
                        $query->where($where)->where('c_user_phone', 'like', '%'.$keywords.'%');
                    })->orWhere(function ($query) use($where, $keywords){
                        $query->where($where)->where('c_address', 'like', '%'.$keywords.'%');
                    })->orWhere(function ($query) use($where, $keywords){
                        $query->where($where)->where('c_numbering', 'like', '%'.$keywords.'%');
                    })
                    ->select($file)
                    ->orderBy('c_id', 'desc')
                    ->paginate($pageLimit);
            }else{
                $list = DB::table($this->customers)
                    ->leftjoin('user', 'c_employees_id', '=', 'u_id')
                    ->leftjoin('department', 'c_store_id', '=', 'id')
                    ->where($where)
                    ->select($file)
                    ->orderBy('c_id', 'desc')
                    ->paginate($pageLimit);
            }
        }

        if(sizeof($list) == 0) {
            return false;
        }
        return $list;
    }
    //根据客源ID  查询该客源的详细信息
    public function customersSameList($c_id, $status = null)
    {
        $file =[$this->customers.'.c_id','c_numbering','c_user_name', 'c_user_phone', 'c_contact', 'c_contact_type', 'c_id_card', 'c_address',
            'c_trading_type', 'c_buy_status', 'c_private_guest', 'c_quality', 'c_secondary_area', 'c_area_address','c_room', 'c_room_json', 'c_position',
            'c_planning', 'c_level', 'c_acreage_max', 'c_acreage_min', 'c_price_max', 'c_price_min',  'c_rent_price_max', 'c_rent_price_min',
            DB::raw('from_unixtime(c_entrust_time) as c_entrust_time'), 'c_entrust_type', 'c_source_type', 'c_user_level', 'c_live_type', 'c_professional_type',
            'c_user_intention', 'c_time_limit', 'c_use_type', 'c_floor', 'c_room_type', 'c_toward', 'c_decorate_type',  'c_payment_type', 'c_complete', 'c_parking',
            'c_situation', 'c_fence', 'c_electricity', 'c_number_of_layers',  'c_industry', 'c_wc', 'c_lot', 'c_pay_type', 'c_remark', 'c_store_id',
            'name', 'c_employees_id', 'u_username','c_store_id','c_employees_id',
            DB::raw('from_unixtime(c_followup_time) as c_followup_time'),
            DB::raw('from_unixtime(c_created_at) as c_created_at'),
            DB::raw('from_unixtime(c_update_at) as c_update_at')
        ] ;
        $where = [];
        if (!$status) {
            $where[] = ['c_status', '=', 1];
        }
        return DB::table($this->customers)
            ->leftjoin('user', 'c_employees_id', '=', 'u_id')
            ->leftjoin('department', 'c_store_id', '=', 'id')
            ->where($this->customers.'.c_id', $c_id)
            ->where($where)
            ->select($file)
            ->first();
    }

    /**
     * @param $c_id
     * @param $pageLimit
     * @param $pcOrApp  PC 传0   APP 传1
     * @return bool
     */
    public function customersFollow($c_id, $pageLimit, $pcOrApp=0)
    {
        if($pcOrApp == 1) { //app
            $list = DB::table($this->customersfollow)
                ->leftJoin('department','cf_department_id','department.id')
                ->leftJoin('user', 'cf_user_id', '=', 'u_id')
                ->where('cf_c_id',$c_id)
                ->select($this->customersfollow.'.cf_id','cf_c_id','cf_fllow_type', 'cf_content', 'u_username','name',
                    DB::raw('from_unixtime(cf_created_at) as cf_created_at'),
                    'cfs_reminder_range as cfs_user_id', 'cfs_remind_time', 'cfs_content','cfs_manager_review')
                ->orderBy($this->customersfollow.'.cf_id', 'desc')
                ->paginate($pageLimit);
        } else {  //PC
            $list = DB::table($this->customersfollow)
                ->leftJoin('department','cf_department_id','department.id')
                ->leftJoin('user', 'cf_user_id', '=', 'u_id')
                ->where('cf_c_id',$c_id)
                ->select($this->customersfollow.'.cf_id','cf_c_id','cf_fllow_type', 'cf_content', 'u_username','name',
                    DB::raw('from_unixtime(cf_created_at) as cf_created_at'),
                    'cfs_reminder_range as cfs_user_id', 'cfs_remind_time', 'cfs_content','cfs_manager_review')
                ->orderBy($this->customersfollow.'.cf_id', 'desc')
                ->paginate($pageLimit);
        }

            if (sizeof($list) == 0) {
                return false;
            }
            foreach ($list as $k => $v) {
                $v->type = 2;
               if ($v->cfs_remind_time) {
                    $v->cfs_remind_time = date('Y-m-d H:i:s', $v->cfs_remind_time);

                } else {
                     $v->cfs_remind_time = '';
                }
//                if ($v->cfs_dealwith_time) {
//                    $v->cfs_dealwith_time = date('Y-m-d H:i:s', $v->cfs_dealwith_time);
//                } else {
//                    $v->cfs_dealwith_time = '';
//                }
            }
        return $list;

    }

    //快速预览跟进
    public function fastcCustomerFollow($c_id){
        return DB::table($this->customersfollow)
            ->leftJoin('user', 'cf_user_id', '=', 'u_id')
            ->where('cf_c_id',$c_id)
            ->select('cf_id','cf_c_id','cf_fllow_type', 'cf_content', 'u_username',
                DB::raw('from_unixtime(cf_created_at) as cf_created_at'))
            ->orderBy('cf_id', 'desc')->take(5)->get();
    }

    //根据客源的手机号  查询该客源是否已经录入过
    public function whether($c_user_phone, $c_id)
    {
        $cid = DB::table($this->customers)
            ->where('c_user_phone', $c_user_phone)
            ->where('c_id', '<>', $c_id)
            ->where('c_status', 1)
            ->value('c_id');
        if ($cid > 0){
            return $cid;
        }
        return false;
    }
    /**
     * 添加客源信息
     */
    public function addCustomers($params)
    {
        $oldPhone = DB::table($this->customers)->where('c_user_phone',$params['c_user_phone'])->value('c_user_phone');
        if($oldPhone){
          return -1;
        }
        $params['c_created_at'] = time();//添加时间
        $params['c_update_at'] = time();//修改时间
        $params['c_followup_time'] = time();//跟进时间

        //开启事务
        DB::beginTransaction();
        $id =  DB::table($this->customers)->insertGetId($params);
        $propertyNumber = 'KY'.$this->branch_id.str_pad($id, 8,0,STR_PAD_LEFT);
        $updateId = DB::table($this->customers)->where('c_id', $id)->update(['c_numbering' => $propertyNumber, 'c_update_at' => time()]);
        if ($id && $updateId) {
            DB::commit();
            $log = new Log();
            $log->addlog($params['c_store_id'], $params['c_employees_id'], 6, '新增客源编号：'.$propertyNumber.' 客户：'.$params['c_user_name']);
            return $id;
        } else {
            DB::rollback();
            return false;
        }

    }
    //客源快速预览信息与跟进
    public function customersFastInfo($cId){
        $data = array();
        $customersinfo =  DB::table($this->customers)
            ->leftJoin('user','u_id','=','c_employees_id')
            ->leftJoin('department','id','=','c_store_id')
            ->where($this->customers.'.c_id',$cId)
            ->select('c_user_name','c_user_phone','c_trading_type','c_secondary_area','c_area_address','c_use_type',
                'c_room','c_remark','name','u_username', DB::raw('from_unixtime(c_entrust_time) as c_entrust_time'),
                'c_private_guest', 'c_employees_id')
            ->first();
//        if($customersinfo->c_private_guest == 1 && $this->uid != $customersinfo->c_employees_id){
//                $customersinfo->c_user_phone = '';
//        }
        if (strlen($customersinfo->c_remark) > 60) {
            $customersinfo->c_remark = mb_substr($customersinfo->c_remark,0,20,'utf-8').'...';
         }

        $data['info'] = '【'.$customersinfo->c_user_name.'】'.' '.$customersinfo->c_user_phone;
        $data['type'] = SystemType::getTypeDetail($customersinfo->c_trading_type).'：'.AreaController::getAreaName($customersinfo->c_secondary_area).' '.
            $customersinfo->c_area_address.' '.SystemType::getTypeDetail($customersinfo->c_use_type).' '.SystemType::getTypeDetail($customersinfo->c_room).'房';
        $data['c_remark'] = $customersinfo->c_remark;
        $data['user'] = $customersinfo->name.' '.$customersinfo->u_username.' '.'['.$customersinfo->c_entrust_time.']'.'委托';
        return $data;

    }

    //获取客源匹配信息
    public function getCustomerInfo($c_id){
        return DB::table($this->customers)->where('c_id',$c_id)
            ->select('c_trading_type','c_secondary_area','c_room','c_use_type','c_acreage_max','c_acreage_min',
                'c_price_max','c_price_min','c_rent_price_max','c_rent_price_min')->first();
    }

    /*
     * 客源智能匹配
     * Wu Ning  000000
     */
    public function customersMatchingRoom($params){
        $where = [];
        $where[] = ['room_status', '=', 1];//过滤非回收站房源

        //交易类型  求租452，求购451，租购453
        //房源出售93，出租94，租购95
      if($params['c_trading_type'] == 452){

            $where[] = ['trading_type', '<>',93];

        }elseif($params['c_trading_type'] == 451){

            $where[] = ['trading_type', '<>',94];
        }
        //用途
        if($params['c_use_type'] != 14){
            $where[] = ['use_type' , $params['c_use_type']];
        }
        //面积
        if(isset($params['c_acreage_min']) && $params['c_acreage_min'] != ''){   //开始面积
            $where[] = ['r_acreage', '>=', $params['c_acreage_min']];
        }
        if(isset($params['c_acreage_max']) && $params['c_acreage_max'] != ''){   //结束面积
            $where[] = ['r_acreage', '<=', $params['c_acreage_max']];
        }


        //价格 交易类型  求租452，求购451，租购453
        if($params['c_trading_type'] == 452){
            //出租
            $where[] = ['rents', '>=', $params['c_rent_price_min']];
            $where[] = ['rents', '<=', $params['c_rent_price_max']];
        }elseif($params['c_trading_type'] == 451){
            //出售
            $where[] = ['price', '>=', $params['c_price_min']];
            $where[] = ['price', '<=', $params['c_price_max']];
        }else{
            //租售
            $where[] = ['rents', '>=', $params['c_rent_price_min']];
            $where[] = ['rents', '<=', $params['c_rent_price_max']];
            $where[] = ['price', '>=', $params['c_price_min']];
            $where[] = ['price', '<=', $params['c_price_max']];
        }
        $roomInfo = new RoomInfo();
        $list = $roomInfo->listRoom(env('PAGE_LIMIT_ADMIN'), $where, '', 0);
        if (!$list) {
           return new NullObject;
        }
        $roomWordbook = new RoomWordbook();
        foreach($list as $k=>$v){
            $v->r_entrust_at = $v->r_entrust_at != null ? date('Y-m-d',$v->r_entrust_at) : '';//委托时间
            $v->making_room = $v->making_room != null ? date('Y-m-d',$v->making_room) : '';//交房时间
            $v->building_s = $v->building_s != null ? date('Y',$v->building_s) : '';//建房年代
            $v->building_name = $roomWordbook->getWordbook($v->building_id); //楼盘字典
            $v->use_name    = SystemType::getTypeDetail($v->use_type);         //用途
            $v->housing_name = SystemType::getTypeDetail($v->housing_types);  //房屋类型
            $v->type_of_house_name = SystemType::getTypeDetail($v->type_of_house_sale);  //房屋出售类型
            $v->disc_name = SystemType::getTypeDetail($v->disc_type);    //盘类型  私盘  公盘
            $v->trading_name = SystemType::getTypeDetail($v->trading_type); //交易类型
            $v->trading_state_name = SystemType::getTypeDetail($v->status); //交易状态类型
            $v->rents_name = SystemType::getTypeDetail($v->rents_type);            //租价类型
            $v->taxes_fees_name = SystemType::getTypeDetail($v->taxes_fees);            //包税费类型
            $v->entrust_name = SystemType::getTypeDetail($v->entrust_way);    //委托方式
            $v->source_name = SystemType::getTypeDetail($v->source_type);    //来源id
            $v->status_quo_name = SystemType::getTypeDetail($v->status_quo);    //现状
            $v->decoration_name = SystemType::getTypeDetail($v->decoration);    //装修
            $v->furniture_name = SystemType::getTypeDetail($v->furniture);    //家具
            $v->appliance_name = SystemType::getTypeDetail($v->appliance);    //家电
            $v->rights_name = SystemType::getTypeDetail($v->rights_type);    //产权类型
            $v->certificate_name = SystemType::getTypeDetail($v->certificate_type);    //证件类型
            $v->payment_name = SystemType::getTypeDetail($v->payment_type);    //付款类型
            $v->pay_on_name = SystemType::getTypeDetail($v->pay_on_type);    //付拥类型
            $v->fence_type_name = SystemType::getTypeDetail($v->fence_type);    //围墙类型
            $v->wc_name = SystemType::getTypeDetail($v->wc_type);    //厕所类型
            $v->dorm_name = SystemType::getTypeDetail($v->dorm_type);    //宿舍类型
            $v->lot_name = SystemType::getTypeDetail($v->lot_type);    //地段类型
            $v->air_name = SystemType::getTypeDetail($v->air_type);    //空调类型
            $v->canteen_name = SystemType::getTypeDetail($v->canteen_type);    //食堂类型
            $v->checking_way_name = SystemType::getTypeDetail($v->checking_way);    //看房方式
            //多选框数据========配套
            $support_name = [];
            if($v->support){
                $support_arr = explode(',',$v->support);
                foreach($support_arr as $key => $val){
                    $support = SystemType::getTypeDetail($val);    //'配套
                    array_push($support_name, $support);
                }
            }
            $v->support_name = implode(',', $support_name);
            //多选框数据========行业
            $industry_name = [];
            if($v->industry_type){
                $industry_arr = explode(',',$v->industry_type);
                foreach($industry_arr as $key => $val){
                    $industry = SystemType::getTypeDetail($val);
                    array_push($industry_name, $industry);
                }
            }
            $v->industry_name = implode(',', $industry_name);
            //根据用途变换的输入款  将数据库json字符串转换成数组
            $v->r_info = json_decode($v->r_info, true);
            //房源明细列表
            $v->r_detaile_list = json_decode($v->r_detaile_list, true);
        }
        return $list;
    }

    /***根据客源ID 修改客源信息
     * @param $params
     * @return mixed
     */
    public function updateCustomers($params)
    {   //验证手机号码重复
        $repeatPhone = DB::table($this->customers)->where('c_user_phone',$params['c_user_phone'])->where('c_id','<>',$params['c_id'])->value('c_user_phone');
        if($repeatPhone){
            return -2;
        }
        //dd($params['c_entrust_time']);
        $params['c_entrust_time'] = strtotime($params['c_entrust_time']);//委托时间
        $params['c_created_at'] = strtotime($params['c_created_at']);//添加时间
        $params['c_update_at'] = time();//修改时间
        //460我租 459我购 455有效
        //判断客源状态，我租或我售需要业绩划分
        if($params['c_buy_status'] == 460 || $params['c_buy_status'] == 459){
            //我租 我购处理
            $oldStatus = DB::table($this->customers)->where('c_id',$params['c_id'])->value('c_buy_status');
            if($params['c_buy_status'] != $oldStatus){
                return -1;//分配业绩
            }else{
                //客源类型变化写入跟进
                DB::beginTransaction();//开启事务
                //客源类型变化写入跟进
                $FollowResult = true;
                $cf_content = $this->updateCustomerAddfoollow($params);
                if ($cf_content != '') {
                    $FollowResult =  DB::table($this->customersfollow)
                        ->insertGetId([
                            'cf_c_id'       => $params['c_id'],
                            'cf_fllow_type' => 12,
                            'cf_content'    => $cf_content,
                            'cf_user_id'    => $this->uid,
                            'cf_department_id' => $this->store_id,
                            'cf_created_at' => time()
                        ]);
                    $params['c_followup_time'] = time();
                }

                $cId =  DB::table($this->customers)
                    ->where('c_id', $params['c_id'])
                    ->update($params);
                if ($FollowResult && $cId) {
                    DB::commit();
                    $log = new Log();
                    $log->addlog($params['c_store_id'], $params['c_employees_id'], 7, '修改客源编号：'.$params['c_numbering'].' 客户：'.$params['c_user_name']);
                    return true;
                } else {
                    DB::rollback();//失败回滚
                    return false;
                }
            }
        }else{
            $oldStatus = DB::table($this->customers)->where('c_id',$params['c_id'])->value('c_buy_status');
            if($oldStatus != 455 && $params['c_buy_status'] == 455){
                //更新委托时间
                //委托时间
                if(isset($params['c_entrust_time']) && isset($params['c_entrust_time']) != ''){
                    $params['c_entrust_time'] = $params['c_entrust_time'];
                }else{
                    $params['c_entrust_time'] = time();
                }

            }
            DB::beginTransaction();//开启事务
            //客源类型变化写入跟进
             $FollowResult = true;
            $cf_content = $this->updateCustomerAddfoollow($params);
            if ($cf_content != '') {
                $FollowResult =  DB::table($this->customersfollow)
                    ->insertGetId([
                        'cf_c_id'       => $params['c_id'],
                        'cf_fllow_type' => 12,
                        'cf_content'    => $cf_content,
                        'cf_user_id'    => $this->uid,
                        'cf_department_id' => $this->store_id,
                        'cf_created_at' => time()
                    ]);
                $params['c_followup_time'] = time();
             }

            $cId =  DB::table($this->customers)
                ->where('c_id', $params['c_id'])
                ->update($params);
            if ($FollowResult && $cId) {
                DB::commit();
                $log = new Log();
                $log->addlog($params['c_store_id'], $params['c_employees_id'], 7, '修改客源编号：'.$params['c_numbering'].' 客户：'.$params['c_user_name']);
                return true;
            } else {
                DB::rollback();//失败回滚
                return false;
            }
        }



    }

    /**
     * 根据客源ID 删除客源信息 同时删除该客源的所有跟进  客源的提醒
     * @param $cId 客源ID
     * @return mixed
     */
    public function delCustomers($cId)
    {
        $cIds = DB::table($this->customers)->where('c_id', $cId)->update(['c_status' => 3]);
        $cfId = DB::table($this->customersfollow)->where('cf_c_id', $cId)->delete();
        $cfsId = DB::table($this->customerfollowsource)->where('cfs_type_id', $cId)->where('cfs_type', 2)->delete();
        $data = DB::table($this->customers)->where('c_id', $cId)->select('c_numbering', 'c_user_name')->first();
        $log = new Log();
        $log->addlog($this->store_id, $this->uid, 8, '删除客源编号：'.$data->c_numbering.' 客户：'.$data->c_user_name);
        if ($cIds) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据客源ID 把客源信息放到回收站
     * @param $cId 客源ID
     * @return mixed 删除人 删除时间
     */
    public function recyclebinCustomers($cId)
    {
        $oldStatus = DB::table($this->customers)->where('c_id',$cId)->value('c_status');
        DB::beginTransaction();//开启事务
        if($oldStatus == 1){
            $newStoaus = 2;
            $cf_fllow_Id =  DB::table($this->customersfollow)
                ->insertGetId([
                    'cf_c_id'       => $cId,
                    'cf_fllow_type' => 12,
                    'cf_content'    => '正常=>回收站',
                    'cf_user_id'    => $this->uid,
                    'cf_department_id' => $this->store_id,
                    'cf_created_at' => time()
                ]);
        }elseif($oldStatus == 2){
            $newStoaus = 1;
            $cf_fllow_Id =  DB::table($this->customersfollow)
                ->insertGetId([
                    'cf_c_id'       => $cId,
                    'cf_fllow_type' => 12,
                    'cf_content'    => '回收站=>正常',
                    'cf_user_id'    => $this->uid,
                    'cf_department_id' => $this->store_id,
                    'cf_created_at' => time()
                ]);
        }else{
            return -1;
        }

        //删除操作添加跟进
        $delResult =  DB::table($this->customers)->where('c_id', $cId)->update(['c_status' => $newStoaus,'c_update_at'=>time()]);
         if ($cf_fllow_Id && $delResult) {
            DB::commit();
            return $delResult;
        } else {
            DB::rollback();
            return false;
        }
    }


    /**中介公司下 回收站客源的信息列表
     * @param $pageLimit
     * @return mixed
     * 客源编号 客源ID 交易 客户姓名 电话 （求购或者求租）区县 （求购或者求租）具体地址 委托日 客源归属 删除时间 删除人部门 删除人
     */
    public  function recycleBinList($pageLimit,$where,$keywords)
    {       
            if($keywords == ''){
                $list = DB::table($this->customers)
                ->leftjoin('user', 'c_employees_id', '=', 'u_id')
                ->where($where)
                ->select('c_numbering','c_id','c_trading_type','c_user_name','c_user_phone','c_secondary_area','c_area_address',
                    DB::raw('from_unixtime(c_entrust_time) as c_entrust_time'), 'u_username')
                ->orderBy('c_update_at', 'desc')
                ->paginate($pageLimit);
              }else{
                $list = DB::table($this->customers)
                    ->leftjoin('user', 'c_employees_id', '=', 'u_id')
                    ->where(function ($query) use($where, $keywords){
                        $query->where($where)->where('c_numbering', 'like', '%'.$keywords.'%');
                    })->orWhere(function ($query) use($where, $keywords) {
                        $query->where($where)->where('c_user_name', 'like', '%'.$keywords.'%');
                    })->orWhere(function ($query) use($where, $keywords){
                        $query->where($where)->where('c_user_phone', 'like', '%'.$keywords.'%');
                    })
                    ->select('c_numbering','c_id','c_trading_type','c_user_name','c_user_phone','c_secondary_area','c_area_address',
                        DB::raw('from_unixtime(c_entrust_time) as c_entrust_time'), 'u_username')
                    ->orderBy('c_update_at', 'desc')
                    ->paginate($pageLimit);
            }
        if (sizeof($list) == 0) {
            return false;
        }
        foreach($list as $key=>$value){
            $value->c_trading_type =  SystemType::getTypeDetail($value->c_trading_type);
            $value->c_secondary_area = AreaController::getAreaName($value->c_secondary_area);

            $delinfo = DB::table($this->customersfollow)
                ->where('cf_c_id','=',$value->c_id)
                ->leftjoin('user','cf_user_id','=','u_id')
                ->leftjoin('department','cf_department_id','=','id')
                ->select(DB::raw('from_unixtime(cf_created_at) as cf_created_at'),'cf_department_id','name','u_username')
                ->orderBy('cf_id', 'desc')->first();
            if ($delinfo != null){
                $value->deltime = $delinfo->cf_created_at;
                $value->deldepartment = $delinfo->name;
                $value->deluser = $delinfo->u_username;
            } else {
                $value->deltime = '';
                $value->deldepartment = '';
                $value->deluser = '';
            }

        }
        return $list;
    }



    /**
     * 修改客源状态信息，增加员工业绩计算
     * 购买状态(455有效 456预定 457已购 458已租 459我购 460我租 461暂缓 462未知 463无效)
     */
    public function saveCustomersStatus($param,$roomId,$type, $money, $rate, $a_uid, $a_remark){
                //客源修改为 459我购 房源修改为101我售
                //客源修改为 460我租 房源修改为102我租
                //开启事务
                DB::beginTransaction();
                if($param['c_buy_status'] == 459){
                    $roomStatus =101;
                }elseif($param['c_buy_status'] == 460){
                    $roomStatus =102;
                }else{
                    return -3;//未知错误
                }
                //修改客源信息
                $param['c_entrust_time'] = strtotime($param['c_entrust_time']);
                $param['c_created_at'] = strtotime($param['c_created_at']);
                $param['c_update_at']  = time();

                //修改客源类型写入跟进
                $FollowResult = true;
                $cf_content = $this->updateCustomerAddfoollow($param);
                if ($cf_content != '') {
                    $FollowResult =  DB::table($this->customersfollow)
                        ->insertGetId([
                            'cf_c_id'       => $param['c_id'],
                            'cf_fllow_type' => 12,
                            'cf_content'    => $cf_content,
                            'cf_user_id'    => $this->uid,
                            'cf_department_id' => $this->store_id,
                            'cf_created_at' => time()
                        ]);
                    $params['c_followup_time'] = time();
                }

                if (is_array($param['c_complete'])) {
                    $param['c_complete'] = implode(',', $param['c_complete']);
                }
                if (is_array($param['c_lot'])) {
                    $param['c_lot'] = implode(',', $param['c_lot']);
                }
                $c_id = DB::table($this->customers)->where('c_id', $param['c_id'])->update($param);

                //修改房源信息
                $r_id = DB::table($this->room_table)->where('id', $roomId)->update(['status' => $roomStatus,'r_updated_at'=>time()]);

                //业绩分配 1独立完成 否则多人协作完成
                if($type == 1){
                    $data['a_room_id']       = $roomId;
                    $data['a_customer_id']   = $param['c_id'];
                    $data['a_uid']           = $a_uid;
                    $data['a_money']         = $money;
                    $data['a_created_at']    = time();
                    $data['a_updated_at']    = time();
                    $data['a_remark']        = $a_remark;
                }else{
                    $data = [];
                    $rate_arr = explode(',' , $rate);
                    $user_id = explode(',' , $a_uid);

                    if (sizeof($rate_arr) != sizeof($user_id)) {
                        return -1;//人员业绩分配不对等，请仔细检查人员的比例分配
                    }
                    $rate = array_sum($rate_arr);
                    if($rate != 100){
                        return -2;//比例分配错误，所有比例总和只能为100
                    }
                    foreach($user_id as $k => $v){
                        $data[$k]['a_uid'] = $v;
                        $data[$k]['a_room_id'] = $roomId;
                        $data[$k]['a_customer_id'] =  $param['c_id'];
                        $data[$k]['a_money'] = floatval($rate_arr[$k]) / $rate * floatval($money);
                        $data[$k]['a_created_at'] = time();
                        $data[$k]['a_updated_at'] = time();
                        $data[$k]['a_remark'] = $a_remark;
                    }
                }
        //添加业绩分配记录
        $a_id = DB::table($this->achievement_table)->insert($data);
        if ($r_id && $c_id && $a_id && $FollowResult) {
            DB::commit();
           //操作日志
            $data = DB::table($this->room_table)
                ->leftjoin($this->room_wordbook, 'building_id', '=', 'w_id')
                ->where('id', $roomId)
                ->select('property_number', 'w_name',  'few_building', 'position', 'room_number')
                ->first();
            $log = new Log();
            $log->addlog($this->store_id, $this->uid, 4, '修改房源编号：'.$data->property_number.' 楼盘：'.$data->w_name.' 栋座：'.$data->few_building.' 位置：'.$data->position.' 房号：'.$data->room_number);
            $log->addlog($this->store_id, $this->uid, 7, '修改客源编号：'.$param['c_numbering'].' 客户：'.$param['c_user_name']);

            return true;
        } else {
            DB::rollback();
            return false;
        }

    }


    /**
     * @param array $map
     * @param $pageLimit
     * @return mixed
     * 员工录入客源排行
     */
    public function customersAchievementList($map = [], $where = [])
    {
        $user_list = DB::table('user')
            ->leftJoin('department', 'u_d_id', '=', 'id')
            ->where('u_b_id', $this->branch_id)
            ->where($where)
            ->where('u_status', 1)
            ->where('user.is_del', 0)
            ->select(['u_id','u_username','name'])
            ->get()
            ->toArray();

        //数据去重
        $user_list = array_map('get_object_vars', $user_list);
        $model = new RoomInfo();
        $user_list = $model->remove_duplicate($user_list);

        foreach($user_list as $k => $v){
            $num = DB::table($this->customers)->where($map)->where('c_employees_id', $v['u_id'])->count();
            $user_list[$k]['num'] = $num;
        }
        $list = json_encode($user_list);
        $list = json_decode($list,true);
        array_multisort(array_column($list,'num'),SORT_DESC,$list);
        return $list;
    }

    /**
     * 添加房源时根据条件智能匹配出对应客源信息
     */
    public function getCustomersList($map, $pageLimit)
    {
        //客源有效状态  455
        $list = DB::table($this->customers)
            ->leftjoin('user', 'c_employees_id', '=', 'u_id')
            ->leftjoin('department', 'c_store_id', '=', 'id')
            ->where($map)
            ->where('c_status', 1)
            ->where('c_buy_status', 455)
            ->select($this->customers.'.c_id', 'c_numbering', 'c_user_name', 'c_user_phone', 'c_contact', 'c_contact_type', 'c_id_card', 'c_address',
                'c_trading_type', 'c_buy_status', 'c_private_guest', 'c_quality', 'c_secondary_area', 'c_area_address', 'c_room_json', 'c_room',  'c_position',
                'c_planning', 'c_level', 'c_acreage_max', 'c_acreage_min', 'c_price_max', 'c_price_min',  'c_rent_price_max', 'c_rent_price_min',
                DB::raw('from_unixtime(c_entrust_time) as c_entrust_time'), 'c_entrust_type', 'c_source_type', 'c_user_level', 'c_live_type', 'c_professional_type',
                'c_user_intention', 'c_time_limit', 'c_use_type', 'c_floor', 'c_room_type', 'c_toward', 'c_decorate_type',  'c_payment_type', 'c_complete', 'c_parking',
                'c_situation', 'c_fence', 'c_electricity', 'c_number_of_layers',  'c_industry', 'c_wc', 'c_lot', 'c_pay_type', 'c_remark', 'c_store_id',
                'name', 'c_employees_id', 'u_username',
                DB::raw('from_unixtime(c_followup_time) as c_followup_time'),
                DB::raw('from_unixtime(c_created_at) as c_created_at'),
                DB::raw('from_unixtime(c_update_at) as c_update_at')
            )
            ->orderBy('c_id', 'desc')
            ->paginate($pageLimit);
        if (sizeof($list) == 0) {
            return '';
        }
        foreach ($list as $key=>$val) {
            $val->c_trading_type_name      = SystemType::getTypeDetail($val->c_trading_type);//交易类型
            $val->c_buy_status_name        = SystemType::getTypeDetail($val->c_buy_status);//购买状态
            //区县名称
            $val->c_secondary_area_name    = AreaController::getAreaName($val->c_secondary_area);
            $val->c_position_name          = SystemType::getTypeDetail($val->c_position);//位置
            $val->c_planning_name          = SystemType::getTypeDetail($val->c_planning);//规划
            $val->c_level_name             = SystemType::getTypeDetail($val->c_level);//级别
            $val->c_entrust_type_name      = SystemType::getTypeDetail($val->c_entrust_type);//委托方式
            $val->c_source_type_name       = SystemType::getTypeDetail($val->c_source_type);//来源
            $val->c_user_level_name        = SystemType::getTypeDetail($val->c_user_level);//等级
            $val->c_live_type_name         = SystemType::getTypeDetail($val->c_live_type);//现住
            $val->c_professional_type_name = SystemType::getTypeDetail($val->c_professional_type);//类别
            $val->c_user_intention_name    = SystemType::getTypeDetail($val->c_user_intention);//意向
            $val->c_time_limit_name        = SystemType::getTypeDetail($val->c_time_limit);//期限
            $val->c_use_type_name          = SystemType::getTypeDetail($val->c_use_type);//用途
            $val->c_room_type_name         = SystemType::getTypeDetail($val->c_room_type);//房屋类型
            $val->c_toward_name            = SystemType::getTypeDetail($val->c_toward);//朝向
            $val->c_decorate_type_name     = SystemType::getTypeDetail($val->c_decorate_type);//装修
            $val->c_payment_type_name      = SystemType::getTypeDetail($val->c_payment_type);//付款
            //配套名字 c_complete
            $c_complete_name = array();//配套名字
            $completeArr = explode(',', $val->c_complete);
            foreach ($completeArr as $ke=>$va) {
                array_push($c_complete_name, SystemType::getTypeDetail($va));
            }
            $val->c_complete_name = implode(',', $c_complete_name);//配套的名字
            $val->c_situation_name      = SystemType::getTypeDetail($val->c_situation);//状况
            $val->c_fence_name      = SystemType::getTypeDetail($val->c_fence);//围墙
            $val->c_number_of_layers_name      = SystemType::getTypeDetail($val->c_number_of_layers);//层数
            $val->c_wc_name      = SystemType::getTypeDetail($val->c_wc);//厕所
            //地段 c_lot
            $c_lot_name = array();
            $lotArr = explode(',', $val->c_lot);
            foreach ($lotArr as $k=>$v) {
                array_push($c_lot_name, SystemType::getTypeDetail($v));
            }
            $val->c_lot_name = implode(',', $c_lot_name);//地段的名字
            $val->c_pay_type_name      = SystemType::getTypeDetail($val->c_pay_type);//付佣
        }

        return $list;
    }


    /**
     * @param $param
     * 自动更新客源对应信息
     */
    public function updateRuleCustomers($param){
        $map = $this->dateMap($param);
        return $this->saveCustomersAuth($map, $param);
    }

    /**
     * @param $param
     * @return array
     * 日期类型判断条件
     */
    public function dateMap($param){
        $map = [];
        $times = time() - 60 * 60 * 24 * $param['a_day_num'];
        switch($param['a_date_type']){   //判断查找时间类型
            case 0: //最后跟进日期
                $map[] = ['c_followup_time', '<=', $times];
                break;
            case 1: //委托日
                $map[] = ['c_entrust_time', '<=', $times];
                break;
            case 2:  //录入日
                $map[] = ['c_created_at', '<=', $times];
                break;
            default:
                break;
        }
        return $map;
    }
    /**
     * @param $map
     * @param $params
     * @return mixed
     * 修改客源私-公
     */
    public function saveCustomersAuth($map, $params){

        $map[] = ['c_private_guest', $this->private_cus];
        if(isset($params['a_d_id']) && $params['a_d_id'] != 0  && $params['a_d_id'] != ''){  //部门ID
            $map[] = ['c_store_id', $params['a_d_id']];
        }
        //以下所有判断如果类型值为false则代表全部，不作为过滤条件
        if(isset($params['a_trade_type']) && $params['a_trade_type'] != 0  && $params['a_trade_type'] != ''){  //交易类型
            $map[] = ['c_trading_type', $params['a_trade_type']];
        }
        if(isset($params['a_m_status']) && $params['a_m_status'] != 0  && $params['a_m_status'] != ''){   //客源状态
            $map[] = ['c_buy_status', $params['a_m_status']];
        }
        if(isset($params['a_use_type']) && $params['a_use_type'] != 0 && $params['a_use_type'] != ''){  //客源用途
            $map[] = ['c_use_type', $params['a_use_type']];
        }
        //操作日志
        $log = new Log();
        $connect = '手动执行 => '.'超过'.$params['a_day_num'].'天,私客转公客';
        $log->addlog($this->store_id,$this->uid,13,$connect);
        if(isset($params['a_entrust_way']) && $params['a_entrust_way'] != 0 && $params['a_entrust_way'] != ''){  //委托方式
            $entrust_arr = explode(',', $params['a_entrust_way']);
            return DB::table($this->customers)
                ->where($map)
                ->whereIn('c_entrust_type', $entrust_arr)
                ->update([
                'c_private_guest' => $this->comm_cus,
                'c_update_at'      => time()
            ]);
        }else{
            return DB::table($this->customers)->where($map)->update([
                'c_private_guest' => $this->comm_cus,
                'c_update_at'      => time()
            ]);
        }

    }

    /**
     * @param $param
     * @param $type
     * @return mixed
     * 移动客源
     */
    public function moves($param, $type){
        $map = $this->moveMap($param);
        if($type == 1 ){
            if($param['num'] > 0){  //如果转移数量大于0则按条件获取固定数量的数据
                $ids = DB::table($this->customers)
                        ->where($map)
                        ->limit($param['num'])
                        ->orderBy('c_id', 'desc')
                        ->pluck('c_id');
                return DB::table($this->customers)
                    ->whereIn('c_id', $ids)
                    ->update([
                        'c_store_id' => $param['to_d_id'],
                        'c_employees_id' => $param['to_uid'],
                        'c_update_at' => time()
                    ]);
            }else{
                return DB::table($this->customers)
                    ->where($map)
                    ->update([
                        'c_store_id' => $param['to_d_id'],
                        'c_employees_id' => $param['to_uid'],
                        'c_update_at' => time()
                    ]);
            }

        }else{
            if($param['num'] > 0){  //如果转移数量大于0则按条件获取固定数量的数据
                return DB::table($this->customers)
                    ->where($map)
                    ->limit($param['num'])
                    ->orderBy('c_id', 'desc')
                    ->pluck('c_id');
            }else{
                return DB::table($this->customers)
                    ->where($map)
                    ->orderBy('c_id', 'desc')
                    ->pluck('c_id');
            }
        }
    }

    /**
     * @param $param
     * @return array
     * 判断条件
     */
    public function moveMap($param){
        $map[] = ['c_store_id', $param['out_d_id']];  //部门ID
        $map[] = ['c_employees_id', $param['out_uid']];  //用户ID
        $map[] = ['c_status', 1];
        //区县Id
        if(isset($param['a_id']) && $param['a_id'] != 0){
            $map[] = ['c_secondary_area', $param['a_id']];//区县
        }
        if(isset($param['c_trading_type']) && $param['c_trading_type'] != ''){ //交易类型 求购 求租 租购
            $map[] = ['c_trading_type', $param['c_trading_type']];
        }
        if(isset($param['c_buy_status']) && $param['c_buy_status'] != ''){  //客源状态
            $map[] = ['c_buy_status', $param['c_buy_status']];
        }
        //按跟进时间
        if(isset($param['start_time']) && $param['start_time'] != ''){ //开始时间
            $map[] = ['c_followup_time', '>=', strtotime($param['start_time'])];
        }
        if(isset($param['end_time']) && $param['end_time'] != ''){  //结束时间
            $map[] = ['c_followup_time', '<=', strtotime($param['end_time'])];
        }
        return $map;
    }

    /**
     * @param $params
     * @return mixed
     * 公到私  私到公
     */
    public function turns($params){
        $map = $this->dateMap($params); //时间数组

        //部门
        if(isset($params['a_d_id']) && $params['a_d_id'] != ''){
            $map[] = ['c_store_id', $params['a_d_id']];
        }
        //员工
        if(isset($params['a_uid']) && $params['a_uid'] != ''){
            $map[] = ['c_employees_id', $params['a_uid']];
        }
        //区域
        if(isset($params['a_code']) && $params['a_code'] != ''){
            $map[] =['c_secondary_area', $params['a_code']] ;
        }
        //交易类型
        if(isset($params['trading_type']) && $params['trading_type'] != ''){
            $map[] = ['c_trading_type', $params['trading_type']];
        }
        //状态
        if(isset($params['status']) && $params['status'] != ''){
            $map[] = ['c_buy_status', $params['status']];
        }
        $updateData = [ 'c_update_at' => time()];
        if($params['turn_type'] == 2){   //私转公
            $map[] = ['c_private_guest', $this->private_cus];
            $updateData = [
                'c_private_guest' => $this->comm_cus,
                'c_update_at' => time()
            ];
        } elseif($params['turn_type'] == 3){  //公转私
           $map[] = ['c_private_guest', $this->comm_cus];
            $updateData = [
                'c_private_guest' => $this->private_cus,
                'c_update_at' => time()
            ];
        }

         $res =  DB::table($this->customers)
            ->where($map)
            ->update($updateData);

        return $res;

    }

    /**
     * 添加 、修改标记
     */
    public function addplan($params){
//        $hmp_data = DB::table($this->mobile_plan)
//            ->where('hmp_room_customer', $params['hmp_room_customer'])//客源1  房源2
//            ->where('hmp_room_customer_id', $params['hmp_room_customer_id'])  // 客源、房源的ID
//            ->where('hmp_user_id', $params['hmp_user_id'])//用户的ID
//            ->select('hmp_id', 'hmp_sign_type')
//            ->first();
//        $hmp_id = $hmp_data->hmp_id;
//        $params['hmp_update_time'] = time();
//        //每一个任务里面  只能有一个客源     取消一个任务里面的客源   删除这个任务里面所有的房源
//        if ($params['hmp_room_customer'] == 1) {//客源
//
//            if ($params['hmp_sign_type'] != 0) { //如果标记有值，则说明不是添加就是修改
//                DB::table($this->mobile_plan)->where('hmp_user_id', $params['hmp_user_id'])->where('hmp_room_customer', 1)
//                    ->where('hmp_sign_type', $params['hmp_sign_type'])->delete();
//                if ($hmp_id) {//修改客源
//                    return DB::table($this->mobile_plan)->where('hmp_id', $hmp_id)->update($params);
//                } else {//添加客源任务
//                    $params['hmp_created_time'] = time();
//                    return DB::table($this->mobile_plan)->insert($params);
//                }
//            } else {//删除客源任务
//                if ($hmp_id) {
//                    return DB::table($this->mobile_plan)->where('hmp_id', $hmp_id)->delete();
//                }
//                return true;
//            }
//        } elseif($params['hmp_room_customer'] == 2) {//房源
//            if ($params['hmp_sign_type'] != 0) {//如果标记有值，则说明不是添加就是修改
//                if ($hmp_id) {
//                    return DB::table($this->mobile_plan)->where('hmp_id', $hmp_id)->update($params);
//                }
//                $params['hmp_created_time'] = time();
//                return DB::table($this->mobile_plan)->insert($params);
//            } else {//如果标记没有值，则说明是删除
//                if ($hmp_id) {
//                    return DB::table($this->mobile_plan)->where('hmp_id', $hmp_id)->delete();
//                }
//                return true;
//            }
//        } else{
//            return false;
//        }

        $hmp_id = DB::table($this->mobile_plan)
            ->where('hmp_room_customer', $params['hmp_room_customer'])//客源1  房源2
            ->where('hmp_room_customer_id', $params['hmp_room_customer_id'])  // 客源、房源的ID
            ->where('hmp_user_id', $params['hmp_user_id'])//用户的ID
            ->value('hmp_id');
        if ($params['hmp_room_customer'] == 1 && $params['hmp_sign_type'] != 0) {//客源
            //如果标记有值，则说明不是添加就是修改
          DB::table($this->mobile_plan)->where('hmp_user_id', $params['hmp_user_id'])->where('hmp_room_customer', 1)
                ->where('hmp_sign_type', $params['hmp_sign_type'])->where('hmp_id', '<>', $hmp_id)->delete();
        }
        if ($params['hmp_sign_type'] != 0) {//如果标记有值，则说明不是添加就是修改
            $params['hmp_update_time'] = time();
            if ($hmp_id) {
                return DB::table($this->mobile_plan)->where('hmp_id', $hmp_id)->update($params);
            } else {
                $params['hmp_created_time'] = time();
                return DB::table($this->mobile_plan)->insert($params);
            }
        } else {//如果标记没有值，则说明是删除
            if ($hmp_id) {
                return DB::table($this->mobile_plan)->where('hmp_id', $hmp_id)->delete();
            }
            return true;
        }
    }

    //移动端获取个人信息
    function getPersonalInfo($uid){
        return  DB::table('user')
            ->leftJoin('staff', 'u_id', '=', 'area_manager_id')
            ->where('u_id', $uid)
            ->select('u_username', 'u_account_number', 'sex', 'phone', 'avatar')
            ->first();

    }

    /**
     * 修改客源的信息  添加到跟进里面去
     */
    public function updateCustomerAddfoollow($param)
    {
        /*
         * 客户姓名 电话 联系人姓名 电话 交易类型 购买状态 公私客 优质客 二级区域 具体地址 房型json 面积大 面积小 购价大 购价小 租价大 租价小
         * 委托时间 委托方式 来源 用途 付款类型 备注 付佣 归属部门 归属员工
         */
        $follow = '';
        $oldData = DB::table($this->customers)->where('c_id',$param['c_id'])->select('c_user_name','c_user_phone','c_contact','c_contact_type',
            'c_trading_type','c_buy_status','c_private_guest','c_quality','c_secondary_area','c_area_address','c_room','c_acreage_max',
            'c_acreage_min','c_price_max','c_price_min','c_rent_price_max','c_rent_price_min','c_entrust_time','c_entrust_type','c_source_type',
            'c_use_type','c_payment_type','c_remark','c_pay_type','c_store_id','c_employees_id')
            ->first();
        //客户姓名
        if($oldData->c_user_name != $param['c_user_name']){
            $follow .= '客户姓名：'.$oldData->c_user_name.' => '.$param['c_user_name'].' ';
        }
        //客户电话
        if($oldData->c_user_phone != $param['c_user_phone']){
            $follow .= '客户电话：'.$oldData->c_user_phone.' => '.$param['c_user_phone']. ' ';
        }
        //联系人姓名
        if(isset($param['c_contact']) && $oldData->c_contact != $param['c_contact']){
            $follow .= '联系人姓名：'.$oldData->c_contact.' => '.$param['c_contact']. ' ';
        }
        //联系人电话
        if(isset($param['c_contact_type']) && $oldData->c_contact_type != $param['c_contact_type']){
            $follow .= '联系人电话：'.$oldData->c_contact_type.' => '.$param['c_contact_type']. ' ';
        }
        //交易类型
        if($oldData->c_trading_type != $param['c_trading_type']){
            $follow .= '交易类型：'.SystemType::getTypeDetail($oldData->c_trading_type).' => '.SystemType::getTypeDetail($param['c_trading_type']). ' ';
        }
        //购买状态
        if($oldData->c_buy_status != $param['c_buy_status']){
            $follow .= '状态：'.SystemType::getTypeDetail($oldData->c_buy_status).' => '.SystemType::getTypeDetail($param['c_buy_status']). ' ';
        }
        //公私客
        if($oldData->c_private_guest != $param['c_private_guest']){
            $follow .= '私客：'.SystemType::getTypeDetail($oldData->c_private_guest).' => '.SystemType::getTypeDetail($param['c_private_guest']). ' ';
        }
        //优质客
        if(isset($param['c_quality']) && $oldData->c_quality != $param['c_quality']){
            $follow .= '优质客：'.SystemType::getTypeDetail($oldData->c_quality).' => '.SystemType::getTypeDetail($param['c_quality']). ' ';
        }
        //区县
        if($oldData->c_secondary_area != $param['c_secondary_area']){
            $follow .= '区县：'.SystemType::getTypeDetail($oldData->c_secondary_area).' => '.SystemType::getTypeDetail($param['c_secondary_area']). ' ';
        }
        //具体地址
        if($oldData->c_area_address != $param['c_area_address']){
            $follow .= '求购地址：'.$oldData->c_area_address.' => '.$param['c_area_address']. ' ';
        }
        //房型json
//        if($oldData->c_room != $param['c_room']){
//            $follow .= '房型：'.$oldData->c_room.'房'.' => '.$param['c_room']. '房  ';
//        }
        //面积大
        if($oldData->c_acreage_max != $param['c_acreage_max']){
            $follow .= '最大面积：'.$oldData->c_acreage_max.'㎡'.' => '.$param['c_acreage_max']. '㎡  ';
        }
        //面积小
        if($oldData->c_acreage_min != $param['c_acreage_min']){
            $follow .= '最小面积：'.$oldData->c_acreage_min.'㎡'.' => '.$param['c_acreage_min']. '㎡  ';
        }
        //购价大
        if($oldData->c_price_max != $param['c_price_max']){
            $follow .= '购房最大价格：'.$oldData->c_price_max.'万元'.' => '.$param['c_price_max']. '万元  ';
        }
        //购价小
        if($oldData->c_price_min != $param['c_price_min']){
            $follow .= '购房最小价格：'.$oldData->c_price_min.'万元'.' => '.$param['c_price_min']. '万元  ';
        }
        //租价大
        if($oldData->c_rent_price_max != $param['c_rent_price_max']){
            $follow .= '租房最大价格：'.$oldData->c_rent_price_max.'元'.' => '.$param['c_rent_price_max']. '元  ';
        }
        //租价小
        if($oldData->c_rent_price_min != $param['c_rent_price_min']){
            $follow .= '租房最小价格：'.$oldData->c_rent_price_min.'元'.' => '.$param['c_rent_price_min']. '元  ';
        }
        //委托时间
        if($oldData->c_entrust_time != $param['c_entrust_time']){
            $follow .= '委托时间：'.date('Y-m-d ',$oldData->c_entrust_time).' => '.date('Y-m-d',$param['c_entrust_time']). ' ';
        }
        //委托方式
//        if($oldData->c_entrust_type != $param['c_entrust_type']){
//            $follow .= '委托方式：'.SystemType::getTypeDetail($oldData->c_entrust_type).' => '.SystemType::getTypeDetail($param['c_entrust_type']). ' ';
//        }
        //来源
        if($oldData->c_source_type != $param['c_source_type']){
            $follow .= '来源：'.SystemType::getTypeDetail($oldData->c_source_type).' => '.SystemType::getTypeDetail($param['c_source_type']). ' ';
        }
        //用途
        if($oldData->c_use_type != $param['c_use_type']){
            $follow .= '用途：'.SystemType::getTypeDetail($oldData->c_use_type).' => '.SystemType::getTypeDetail($param['c_use_type']). ' ';
        }
        //付款类型
        if(isset($param['c_payment_type']) && $oldData->c_payment_type != $param['c_payment_type']){
            $follow .= '付款类型：'.SystemType::getTypeDetail($oldData->c_payment_type).' => '.SystemType::getTypeDetail($param['c_payment_type']). ' ';
        }
        //备注
        if(isset($param['c_remark']) && $oldData->c_remark != $param['c_remark']){
            $follow .= '备注：'.$oldData->c_remark.' => '.$param['c_remark']. ' ';
        }
        //付佣
        if(isset($param['c_pay_type']) && $oldData->c_pay_type != $param['c_pay_type']){
            $follow .= '付佣：'.SystemType::getTypeDetail($oldData->c_pay_type).' => '.SystemType::getTypeDetail($param['c_pay_type']). ' ';
        }
        //归属部门
        if($oldData->c_store_id != $param['c_store_id']){
            $follow .= '部门：'.Department::getDeparName($oldData->c_store_id).' => '.Department::getDeparName($param['c_store_id']). ' ';
        }
        //归属员工
        if($oldData->c_employees_id != $param['c_employees_id']){
            $follow .= '员工：'.User::getUserNameForId($oldData->c_employees_id).' => '.User::getUserNameForId($param['c_employees_id']). ' ';
        }

        return $follow;

    }
        //通过Id获取客源详情
    public function getCustomersDetail($id){
        $customers = new Customers();
        $detail = $customers->customersSameList($id, 1);

        $uId =  $this->uid;
        if(!$detail){
            return $this->error(Error::INVALID_ARUGMENT);
        }
        $detail->c_secondary_area_name   = AreaController::getAreaName($detail->c_secondary_area);//区县
        $detail->c_trading_type_name      = SystemType::getTypeDetail($detail->c_trading_type);//交易类型
        $detail->c_buy_status_name        = SystemType::getTypeDetail($detail->c_buy_status);//购买状态
        $detail->c_source_type_name       = SystemType::getTypeDetail($detail->c_source_type);//来源
        $detail->c_entrust_type_name      = SystemType::getTypeDetail($detail->c_entrust_type);//委托方式
        $detail->c_user_level_name        = SystemType::getTypeDetail($detail->c_user_level);//等级
        $detail->c_live_type_name         = SystemType::getTypeDetail($detail->c_live_type);//现住
        $detail->c_professional_type_name = SystemType::getTypeDetail($detail->c_professional_type);//类别
        $detail->c_user_intention_name    = SystemType::getTypeDetail($detail->c_user_intention);//意向
        $detail->c_time_limit_name        = SystemType::getTypeDetail($detail->c_time_limit);//期限
        $detail->c_use_type_name          = SystemType::getTypeDetail($detail->c_use_type);//用途
        $detail->c_room_type_name         = SystemType::getTypeDetail($detail->c_room_type);//房屋类型
        $detail->c_toward_name            = SystemType::getTypeDetail($detail->c_toward);//朝向
        $detail->c_decorate_type_name     = SystemType::getTypeDetail($detail->c_decorate_type);//装修
        $detail->c_payment_type_name      = SystemType::getTypeDetail($detail->c_payment_type);//付款
        //房型
        //配套名字 c_complete
        $c_complete_name = array();//配套名字
        $completeArr = explode(',', $detail->c_complete);
        foreach ($completeArr as $ke=>$va) {
            array_push($c_complete_name, Type::getTypeDetail($va));
        }
        $detail->c_complete_name = implode(',', $c_complete_name);//配套的名字
        $detail->c_pay_type_name      = Type::getTypeDetail($detail->c_pay_type);//付佣

        return $detail;
    }
    //通过提醒id客源提醒
    public function getCustomersRemind($id){
            $res = DB::table($this->customerfollowsource)
            ->leftJoin($this->customersfollow, $this->customerfollowsource.'.cf_id', '=', $this->customersfollow.'.cf_id')
            ->leftJoin('user','cf_user_id','u_id')
            ->leftJoin('department','cf_department_id','id')
            ->where('cfs_id',$id)
            ->select($this->customerfollowsource.'.cf_id','cf_c_id','cf_fllow_type','cf_room_id','cf_content','u_username','name',
                DB::raw('from_unixtime(cf_created_at) as cf_created_at'),'cfs_user_id',DB::raw('from_unixtime(cfs_remind_time) as cfs_remind_time'),
                'cfs_content','cfs_deal_with','cfs_dealwith_pro','cfs_dealwith_time','cfs_manager_review')
            ->first();
        $res->reminded_name = DB::table('user')->where('u_id',$res->cfs_user_id)->value('u_username');
            return $res;
    }

    //通过跟进Id 获取跟进
    public function getCustomersFollows($cf_id){
        $list = DB::table($this->customersfollow)
                        ->where('cf_id',$cf_id)
                        ->select('cf_id','cf_c_id','cf_fllow_type','cf_room_id','cf_content',
                            'cf_user_id','cf_department_id',DB::raw('from_unixtime(cf_created_at) as cf_created_at'),
                            'cfs_remind_time','cfs_content','cfs_manager_review','cfs_reminder_range')
                        ->first();

        if($list->cf_room_id != 0){
            $roonInfo = DB::table($this->room_table)->where('id',$list->cf_room_id)->select('property_number','building_id','few_building','position','r_acreage')->first();
            $roomWordbook = new RoomWordbook();
            $roonInfo->building_name = $roomWordbook->getWordbook($roonInfo->building_id);
            $list->cf_room_id_info = $roonInfo->property_number.' '.$roonInfo->building_name.' '.$roonInfo->few_building.' '.$roonInfo->position.' '.$roonInfo->r_acreage.'㎡';
        }

        if (sizeof($list) == 0) {
            return false;
        }
        if($list->cfs_remind_time != null){
            $cfs_deal_with = DB::table($this->customerfollowsource)->where('cf_id',$cf_id)
                ->where('cfs_type',2)
                ->where('cfs_user_id',$this->uid)
                ->value('cfs_deal_with');

            if($this->uid == $list->cf_user_id && $cfs_deal_with == 1){
                $SourceData = DB::table($this->customerfollowsource)
                    ->leftJoin('user','cfs_dealwith_pro','u_id')
                    ->where('cf_id',$cf_id)
                    ->where('cfs_type',2)
                    ->where('cfs_user_id',$this->uid)
                    ->select('cfs_deal_with','u_username','cfs_dealwith_time')
                    ->first();
                $list->cfs_deal_with = $SourceData->cfs_deal_with;
                $list->cfs_dealwith_pro = $SourceData->u_username;
                $list->cfs_dealwith_time = date('Y-m-d H:i:s',$SourceData->cfs_dealwith_time);
            }
        }

        if($list->cfs_remind_time){
            $list->cfs_remind_time = date('Y-m-d H:i:s', $list->cfs_remind_time);

        }else{
            $list->cfs_remind_time = '';
        }
        $list->cfs_user_id =  $list->cfs_reminder_range;
        return $list;
    }


    /**APP 首页  检索条件
     * @param array $where  客源的权限过滤条件
     * @param array $map    房源的权限过滤条件
     */
    public function getListForKeywords($where = [], $map = [], $uid, $authories)
    {
        //客源
        $file =[$this->customers.'.c_id','c_numbering','c_user_name', 'c_user_phone', 'c_contact', 'c_contact_type', 'c_id_card', 'c_address',
            'c_trading_type', 'c_buy_status', 'c_private_guest', 'c_quality', 'c_secondary_area', 'c_area_address','c_room', 'c_room_json', 'c_position',
            'c_planning', 'c_level', 'c_acreage_max', 'c_acreage_min', 'c_price_max', 'c_price_min',  'c_rent_price_max', 'c_rent_price_min',
            DB::raw('from_unixtime(c_entrust_time) as c_entrust_time'), 'c_entrust_type', 'c_source_type', 'c_user_level', 'c_live_type', 'c_professional_type',
            'c_user_intention', 'c_time_limit', 'c_use_type', 'c_floor', 'c_room_type', 'c_toward', 'c_decorate_type',  'c_payment_type', 'c_complete', 'c_parking',
            'c_situation', 'c_fence', 'c_electricity', 'c_number_of_layers',  'c_industry', 'c_wc', 'c_lot', 'c_pay_type', 'c_remark', 'c_store_id',
            'name', 'c_employees_id', 'u_username','c_store_id','c_employees_id',
            DB::raw('from_unixtime(c_followup_time) as c_followup_time'),
            DB::raw('from_unixtime(c_created_at) as c_created_at'),
            DB::raw('from_unixtime(c_update_at) as c_update_at')
        ] ;
        $list['customersData'] = DB::table($this->customers)
            ->leftjoin('user', 'c_employees_id', '=', 'u_id')
            ->leftjoin('department', 'c_store_id', '=', 'id')
            ->where($where)
            ->select($file)
            ->get();
        if (sizeof($list['customersData']) != 0) {
            $mobilePlan = new MobilePlan();
            foreach ($list['customersData'] as $key=>$val) {
                $val->dataType = 1;//客源
                $follow     =  new CustomersFollow();
                $val->lookStatus = 1;
                //如果是公客   先根据是不是自己的客源做判断 在根据权限做判断 在根据当天有没有写过跟进做判断
                //看客户不必写跟进 163
                if ($val->c_private_guest == 2 &&  $val->c_employees_id != $uid && !in_array(163, $authories)) {
                    //根据客源ID、员工ID  查询当天该员工有没有对该客源写过跟进
                    $res  = $follow->getFollowDay($val->c_id, $uid);
//                //最后跟进的天  不是今天的话
                    if ($res === 2) {
                        $val->lookStatus = $res;
                        $val->c_user_name = '***';
                        $val->c_user_phone = '***********';
                        $val->c_contact = '***';
                        $val->c_contact_type = '***********';
                        $val->c_address = '**************';
                    }
                }
                $val->c_entrust_time = $val->c_entrust_time != null ? substr($val->c_entrust_time, 0,10) : '';//委托时间
                //客源类型是私客 &&没有查看私客的权限 &&录入人不是登录人
                if ($val->c_private_guest == 1 && !in_array(107, $authories) && $val->c_employees_id != $uid) {
                    $val->c_user_name = '***';
                    $val->c_user_phone = '***********';
                    $val->c_contact = '***';
                    $val->c_contact_type = '***********';
                    $val->c_address = '**************';
                }

                    $val->c_secondary_area_name    = AreaController::getAreaName($val->c_secondary_area);//区县
                    $val->c_trading_type_name      = SystemType::getTypeDetail($val->c_trading_type);//交易类型
                    $val->c_buy_status_name        = SystemType::getTypeDetail($val->c_buy_status);//购买状态
                    $val->c_source_type_name       = SystemType::getTypeDetail($val->c_source_type);//来源
                    $val->c_entrust_type_name      = SystemType::getTypeDetail($val->c_entrust_type);//委托方式
                    $val->c_user_level_name        = SystemType::getTypeDetail($val->c_user_level);//等级
                    $val->c_live_type_name         = SystemType::getTypeDetail($val->c_live_type);//现住
                    $val->c_professional_type_name = SystemType::getTypeDetail($val->c_professional_type);//类别
                    $val->c_user_intention_name    = SystemType::getTypeDetail($val->c_user_intention);//意向
                    $val->c_time_limit_name        = SystemType::getTypeDetail($val->c_time_limit);//期限
                    $val->c_use_type_name          = SystemType::getTypeDetail($val->c_use_type);//用途
                    $val->c_room_type_name         = SystemType::getTypeDetail($val->c_room_type);//房屋类型
                    $val->c_toward_name            = SystemType::getTypeDetail($val->c_toward);//朝向
                    $val->c_decorate_type_name     = SystemType::getTypeDetail($val->c_decorate_type);//装修
                    $val->c_payment_type_name      = SystemType::getTypeDetail($val->c_payment_type);//付款
                    //配套名字 c_complete
                    $c_complete_name = array();//配套名字
                    $completeArr = explode(',', $val->c_complete);
                    foreach ($completeArr as $ke=>$va) {
                        array_push($c_complete_name, Type::getTypeDetail($va));
                    }
                    $val->c_complete_name = implode(',', $c_complete_name);//配套的名字
                    $val->c_pay_type_name      = Type::getTypeDetail($val->c_pay_type);//付佣
                    //查标记
                    $hmp_sign_type = $mobilePlan->getSignType(1, $val->c_id, $uid);
                    $val->hmp_sign_type = $hmp_sign_type?$hmp_sign_type:0;
                }
        }
        //房源
        $field = [$this->room_table.'.id', 'property_number','building_id','few_building', 'position', 'room_number', 'floor','total_layer',
            'r_info', 'r_acreage', 'use_type', 'housing_types', 'type_of_house_sale', 'building_s', 'disc_type',  'trading_type',
            'status', 'price',  'unit_price','sale_floor_price', 'rents_type', 'rents', 'rents_unit_price', 'floor_price',
            'taxes_fees', 'some_price', DB::raw('from_unixtime(r_entrust_at) as r_entrust_at'), 'entrust_way', 'admin_cost',
            DB::raw('from_unixtime(making_room) as making_room'), 'entrust_number', 'source_type', 'status_quo', 'decoration',
            'support','furniture','appliance', 'rights_type', 'certificate_type', 'payment_type', 'pay_on_type', 'fence_type',
            'industry_type', 'wc_type', 'dorm_type', 'lot_type', 'air_type', 'canteen_type', 'checking_way', 'checking_remark',
            'owner_name', 'owner_phone', 'contact_name', 'contact_phone', 'remark', 'r_d_id','source_uid', 'r_detaile_list',
            'u_username', 'name','r_follow_time',
        ];
        $list['roomData'] = DB::table($this->room_table)
            ->leftjoin('user', 'source_uid', '=', 'u_id')
            ->leftjoin('department', 'r_d_id', '=', 'department.id')
            ->where($map)
            ->select($field)
            ->get();
        $roomWordbook = new RoomWordbook();
        if (sizeof($list['roomData']) != 0) {
            $mobilePlan = new MobilePlan();
            foreach ($list['roomData'] as $k=>$v) {
                $v->dataType = 2;//房源
                if (!in_array(51, $authories) && $v->disc_type == 36 && $v->source_uid != $uid) {//私盘
                    $v->room_number = '****'; //房号
                    $v->owner_name = '***'; //业主姓名
                    $v->owner_phone = '***********'; //业主电话
                    $v->contact_name = '***'; //联系人姓名
                    $v->contact_phone = '***********'; //联系人电话
                }
                if (!in_array(52, $authories) && $v->disc_type == 38 && $v->source_uid != $uid) {//特盘
                    $v->room_number = '****'; //房号
                    $v->owner_name = '***'; //业主姓名
                    $v->owner_phone = '***********'; //业主电话
                    $v->contact_name = '***'; //联系人姓名
                    $v->contact_phone = '***********'; //联系人电话
                }
                if (!in_array(53, $authories) && $v->disc_type == 39 && $v->source_uid != $uid) {//下定盘
                    $v->room_number = '****'; //房号
                    $v->owner_name = '***'; //业主姓名
                    $v->owner_phone = '***********'; //业主电话
                    $v->contact_name = '***'; //联系人姓名
                    $v->contact_phone = '***********'; //联系人电话
                }
                if (!in_array(54, $authories) && $v->disc_type == 708 && $v->source_uid != $uid) {//斡旋盘
                    $v->room_number = '****'; //房号
                    $v->owner_name = '***'; //业主姓名
                    $v->owner_phone = '***********'; //业主电话
                    $v->contact_name = '***'; //联系人姓名
                    $v->contact_phone = '***********'; //联系人电话
                }
                if (!in_array(164, $authories) && $v->disc_type == 37 && $v->source_uid != $uid) {//封盘
                    $v->room_number = '****'; //房号
                    $v->owner_name = '***'; //业主姓名
                    $v->owner_phone = '***********'; //业主电话
                    $v->contact_name = '***'; //联系人姓名
                    $v->contact_phone = '***********'; //联系人电话
                }

                //如果是公盘   先根据是不是自己的房源做判断 在根据权限做判断 在根据当天有没有写过跟进做判断
                //看业主不必写跟进 162
                $v->lookStatus = 1;//lookStatus == 1不用写跟进   == 2 公盘可能需要写跟进
                if ($v->disc_type == 35 &&  $v->source_uid != $uid && !in_array(162, $authories)) {
                    $rfollow = new RoomFollow();
                    //根据客源ID、员工ID  查询当天该员工有没有对该客源写过跟进
                    $res  = $rfollow->getFollowDay($v->id, $uid);
//                //最后跟进的天  不是今天的话
                    if ($res === 2) {
                        $v->lookStatus = $res;
                        $v->room_number = '****'; //房号
                        $v->owner_name = '***'; //业主姓名
                        $v->owner_phone = '***********'; //业主电话
                        $v->contact_name = '***'; //联系人姓名
                        $v->contact_phone = '***********'; //联系人电话;
                    }
                }
                // $v->making_room = $v->making_room != null ? date('Y-m-d',$v->making_room) : '';//交房日期
                $v->making_room = $v->making_room != null ? $v->making_room : '';//交房日期
                $v->building_s = $v->building_s != null ? date('Y',$v->building_s) : '';//建房年代
                $v->r_follow_time = $v->r_follow_time != null ? date('Y-m-d',$v->r_follow_time) : '';
                $v->building_name = $roomWordbook->getWordbook($v->building_id); //楼盘字典
                $v->use_name    = SystemType::getTypeDetail($v->use_type);         //用途
                $v->housing_name = SystemType::getTypeDetail($v->housing_types);  //房屋类型
                $v->type_of_house_name = SystemType::getTypeDetail($v->type_of_house_sale);  //房屋出售类型
                $v->disc_name = SystemType::getTypeDetail($v->disc_type);    //盘类型  私盘  公盘
                $v->trading_name = SystemType::getTypeDetail($v->trading_type); //交易类型
                $v->trading_state_name = SystemType::getTypeDetail($v->status); //交易状态类型
                $v->rents_name = SystemType::getTypeDetail($v->rents_type);            //租价类型
                $v->taxes_fees_name = SystemType::getTypeDetail($v->taxes_fees);            //包税费类型
                $v->entrust_name = SystemType::getTypeDetail($v->entrust_way);    //委托方式
                $v->source_name = SystemType::getTypeDetail($v->source_type);    //来源id
                $v->status_quo_name = SystemType::getTypeDetail($v->status_quo);    //现状
                $v->decoration_name = SystemType::getTypeDetail($v->decoration);    //装修
                $v->furniture_name = SystemType::getTypeDetail($v->furniture);    //家具
                $v->appliance_name = SystemType::getTypeDetail($v->appliance);    //家电
                $v->rights_name = SystemType::getTypeDetail($v->rights_type);    //产权类型
                $v->certificate_name = SystemType::getTypeDetail($v->certificate_type);    //证件类型
                $v->payment_name = SystemType::getTypeDetail($v->payment_type);    //付款类型
                $v->pay_on_name = SystemType::getTypeDetail($v->pay_on_type);    //付拥类型
                $v->fence_type_name = SystemType::getTypeDetail($v->fence_type);    //围墙类型
                $v->wc_name = SystemType::getTypeDetail($v->wc_type);    //厕所类型
                $v->dorm_name = SystemType::getTypeDetail($v->dorm_type);    //宿舍类型
                $v->lot_name = SystemType::getTypeDetail($v->lot_type);    //地段类型
                $v->air_name = SystemType::getTypeDetail($v->air_type);    //空调类型
                $v->canteen_name = SystemType::getTypeDetail($v->canteen_type);    //食堂类型
                $v->checking_way_name = SystemType::getTypeDetail($v->checking_way);    //看房方式

                //多选框数据========配套
                $support_name = [];
                if($v->support){
                    $support_arr = explode(',',$v->support);
                    foreach($support_arr as $key => $val){
                        $support = SystemType::getTypeDetail($val);    //'配套
                        array_push($support_name, $support);
                    }
                }
                $v->support_name = implode(',', $support_name);
                //多选框数据========行业
                $industry_name = [];
                if($v->industry_type){
                    $industry_arr = explode(',',$v->industry_type);
                    foreach($industry_arr as $key => $val){
                        $industry = SystemType::getTypeDetail($val);
                        array_push($industry_name, $industry);
                    }
                }
                $v->industry_name = implode(',', $industry_name);
                //根据用途变换的输入款  将数据库json字符串转换成数组
                $v->r_info = json_decode($v->r_info, true);
                //房源明细列表
                $v->r_detaile_list = json_decode($v->r_detaile_list, true);
                //查标记
                $hmp_sign_type = $mobilePlan->getSignType(2, $v->id, $uid);
                $v->hmp_sign_type = $hmp_sign_type?$hmp_sign_type:0;
            }
        }
        return $list;
    }
    /**
     * APP处理 和客源列表有关的数据（判断权限）
     */
    public function dealWithData($val, $authories, $uid)
    {
        $mobilePlan =  new MobilePlan();
        $follow     =  new CustomersFollow();
        $val->lookStatus = 1;
        //如果是公客   先根据是不是自己的客源做判断 在根据权限做判断 在根据当天有没有写过跟进做判断
        //看客户不必写跟进 163
        if ($val->c_private_guest == 2 &&  $val->c_employees_id != $uid && !in_array(163, $authories)) {
            //根据客源ID、员工ID  查询当天该员工有没有对该客源写过跟进
            $res  = $follow->getFollowDay($val->c_id, $uid);
//                //最后跟进的天  不是今天的话
            if ($res === 2) {
                $val->lookStatus = $res;
                $val->c_user_name = '***';
                $val->c_user_phone = '***********';
                $val->c_contact = '***';
                $val->c_contact_type = '***********';
                $val->c_address = '**************';
            }
        }
        $val->c_entrust_time = $val->c_entrust_time != null ? substr($val->c_entrust_time, 0,10) : '';//委托时间
        //客源类型是私客 &&没有查看私客的权限 &&录入人不是登录人
        if ($val->c_private_guest == 1 && !in_array(107, $authories) && $val->c_employees_id != $uid) {
            $val->c_user_name = '***';
            $val->c_user_phone = '***********';
            $val->c_contact = '***';
            $val->c_contact_type = '***********';
            $val->c_address = '**************';
        }
        $val->c_secondary_area_name    = AreaController::getAreaName($val->c_secondary_area);//区县
        $val->c_trading_type_name      = SystemType::getTypeDetail($val->c_trading_type);//交易类型
        $val->c_buy_status_name        = SystemType::getTypeDetail($val->c_buy_status);//购买状态
        $val->c_source_type_name       = SystemType::getTypeDetail($val->c_source_type);//来源
        $val->c_entrust_type_name      = SystemType::getTypeDetail($val->c_entrust_type);//委托方式
        $val->c_user_level_name        = SystemType::getTypeDetail($val->c_user_level);//等级
        $val->c_live_type_name         = SystemType::getTypeDetail($val->c_live_type);//现住
        $val->c_professional_type_name = SystemType::getTypeDetail($val->c_professional_type);//类别
        $val->c_user_intention_name    = SystemType::getTypeDetail($val->c_user_intention);//意向
        $val->c_time_limit_name        = SystemType::getTypeDetail($val->c_time_limit);//期限
        $val->c_use_type_name          = SystemType::getTypeDetail($val->c_use_type);//用途
        $val->c_room_type_name         = SystemType::getTypeDetail($val->c_room_type);//房屋类型
        $val->c_toward_name            = SystemType::getTypeDetail($val->c_toward);//朝向
        $val->c_decorate_type_name     = SystemType::getTypeDetail($val->c_decorate_type);//装修
        $val->c_payment_type_name      = SystemType::getTypeDetail($val->c_payment_type);//付款
        //配套名字 c_complete
        $c_complete_name = array();//配套名字
        $completeArr = explode(',', $val->c_complete);
        foreach ($completeArr as $ke=>$va) {
            array_push($c_complete_name, SystemType::getTypeDetail($va));
        }
        $val->c_complete_name = implode(',', $c_complete_name);//配套的名字
        $val->c_pay_type_name      = SystemType::getTypeDetail($val->c_pay_type);//付佣
        //查标记
        $hmp_sign_type = $mobilePlan->getSignType(1, $val->c_id, $uid);
        $val->hmp_sign_type = $hmp_sign_type?$hmp_sign_type:0;
        return $val;
    }

    /**
     * @param $cid
     * APP 写完公客的跟进 根据客源的ID  查询该客源的信息
     * @return mixed
     */
    public function getImportantInfo($cid)
    {
        return  DB::table($this->customers)->where('c_id', $cid)->select('c_user_name', 'c_user_phone', 'c_contact', 'c_contact_type', 'c_address')->first();
    }
}